package com.david.file_manager

import android.app.Activity
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.david.core.utils.FileUtils
import java.io.File

class MainActivity : AppCompatActivity() {
    private val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            Log.e("file", "start page result ")
//            val intent = result.data
            // Handle the Intent
        }
    }

    private val dirs = ArrayList<ArrayList<FileInfo>>()//ele为ArrayList<FileInfo>,二维数组，模拟栈

    private val onItemClick = View.OnClickListener {
        val fileInfo = it.tag as FileInfo
        if (fileInfo.isDir) {
            val subFiles = File(fileInfo.absolutePath).listFiles()//获取子文件夹中的文件列表
            FileUtils.sortFile(subFiles)
            val list = getSortFileInfo(subFiles)
            dirs.add(list)
            adapter.files = list
            adapter.notifyDataSetChanged()
        } else {
            // TODO: 打开相应文件：视频、音频、文档等
        }
    }

    private val adapter: FileAdapter = FileAdapter(onItemClick)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //android11管理所以文件：https://developer.android.google.cn/training/data-storage/manage-all-files?hl=zh-cn, https://juejin.cn/post/7012262477828194340
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //检查是否已经有权限
            if (!Environment.isExternalStorageManager()) {
                //跳转新页面申请权限
                startForResult.launch(
                    Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                )
//                startActivityForResult( Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), 101);
            }
        }


        val recyclerView = findViewById<RecyclerView>(R.id.file_list)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        findViewById<View>(R.id.btn).setOnClickListener {
            //获取所有文件管理权限后可以增删改查文件夹中文件，注：android/data中为app私有目录无法访问
            val files = Environment.getExternalStorageDirectory().listFiles()
            val list = getSortFileInfo(files)
            dirs.add(list)
            adapter.files = list
            adapter.notifyDataSetChanged()
        }
    }

    override fun onBackPressed() {
        if (dirs.size == 1) {
            super.onBackPressed()
        } else {//判断是能返回上一层文件夹，在根文件列表时退出app
            dirs.removeLast()
            adapter.files = dirs[dirs.size - 1]
            adapter.notifyDataSetChanged()
        }
    }

    private fun getSortFileInfo(files: Array<File>): ArrayList<FileInfo> {
        FileUtils.sortFile(files)
        val list = ArrayList<FileInfo>()
        for (item in files) {
            list.add(FileInfo(item.name, item.absolutePath, item.extension, !item.isFile, if (!item.isFile) R.mipmap.ic_dir else R.mipmap.ic_launcher))
        }
        return list
    }
}

class FileAdapter(private var onItemClick: View.OnClickListener) : RecyclerView.Adapter<FileHolder>() {
    var files = ArrayList<FileInfo>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_file, parent, false)
        view.setOnClickListener(onItemClick)
        return FileHolder(view)
    }

    override fun onBindViewHolder(holder: FileHolder, position: Int) {
        holder.img.setImageResource(files[position].imgRes)
        holder.title.text = files[position].name

        holder.itemView.tag = files[position]
    }

    override fun getItemCount(): Int {
        return files.size
    }

}

class FileHolder(itemView: View):RecyclerView.ViewHolder(itemView){
    var img: ImageView = itemView.findViewById(R.id.item_file_img)
    var title: TextView = itemView.findViewById(R.id.item_file_title)
}